package net.sx.minemodule.mvp.activities;

import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.RelativeSizeSpan;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.homegoods.aroutercomment.ARouterPath;
import com.kedll.library.base.MyBaseFragmentActivity;
import com.kedll.library.util.ToastUtil;

import net.sx.minemodule.R;
import net.sx.minemodule.adapter.OrderDetailAdapter;
import net.sx.minemodule.databinding.MineActivityMineOrderDetailBinding;
import net.sx.minemodule.mvp.bean.OrderListDetailBean;
import net.sx.minemodule.mvp.bean.SectionMultipleItem;
import net.sx.minemodule.mvp.presenters.MineOrderDetailPresenter;
import net.sx.minemodule.mvp.views.MineOrderDetailView;

import java.util.ArrayList;
import java.util.List;

/**
 * 订单详情
 *
 * @author 11470
 */
@Route(path = ARouterPath.PATH_MINE_ORDER_DETAIL)
public class MineOrderDetailActivity extends MyBaseFragmentActivity<MineActivityMineOrderDetailBinding, MineOrderDetailPresenter> implements MineOrderDetailView {

    private String orderId = "";

    private OrderListDetailBean mData;
    private List<SectionMultipleItem> list = new ArrayList<>();
    private OrderDetailAdapter mAdapter;

    private AlertDialog mDialog;

    private RelativeLayout rlRefund;

    @Override
    protected int getLayout() {
        return R.layout.mine_activity_mine_order_detail;
    }

    @Override
    protected void initToolBar(Bundle savedInstanceState) {
        super.initToolBar(savedInstanceState);

        appBarLayout.setBackgroundColor(getResources().getColor(R.color.color_a541c9));
        setTopLeftButton(R.mipmap.mine_ic_arrow_white, v -> {
            finish();
        });
    }

    @Override
    protected MineOrderDetailPresenter getPresenter() {
        return new MineOrderDetailPresenter(this);
    }


    @Override
    protected void initEvent() {

    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        if (getIntent().getExtras() != null) {
            orderId = getIntent().getStringExtra("orderId");
        }
        mPresenter.getOrderDetailInfo(orderId);
        initRefundDialog();
    }


    /**
     * 初始化 退款对话框
     */
    private void initRefundDialog() {
        mDialog = new AlertDialog.Builder(this).create();
        Window window = mDialog.getWindow();
        window.setWindowAnimations(R.style.mine_dialog_window_anim); //设置进入退出动画

        WindowManager.LayoutParams wl = window.getAttributes();
        wl.y = getWindowManager().getDefaultDisplay().getHeight(); //弹出位置

        //设置dialog宽度全屏
        window.getDecorView().setPadding(0, 0, 0, 0);
        window.getDecorView().setBackgroundColor(Color.WHITE);
        wl.width = WindowManager.LayoutParams.MATCH_PARENT;
        wl.horizontalMargin = 0;

        mDialog.onWindowAttributesChanged(wl);
        rlRefund = (RelativeLayout) getLayoutInflater().inflate(R.layout.mine_dialog_refund, (ViewGroup) getWindow().getDecorView(), false);
        setRefundDialogClick(rlRefund);

        mDialog.setView(rlRefund);
    }

    private String canCelTag;

    private void setRefundDialogClick(RelativeLayout rlFeedback) {
        RelativeLayout rlRadio1 = (RelativeLayout) rlFeedback.findViewById(R.id.rl_radio1);
        RelativeLayout rlRadio2 = (RelativeLayout) rlFeedback.findViewById(R.id.rl_radio2);
        RelativeLayout rlRadio3 = (RelativeLayout) rlFeedback.findViewById(R.id.rl_radio3);
        RelativeLayout rlRadio4 = (RelativeLayout) rlFeedback.findViewById(R.id.rl_radio4);
        RelativeLayout rlRadio5 = (RelativeLayout) rlFeedback.findViewById(R.id.rl_radio5);

        ImageView imgRadio1 = (ImageView) rlFeedback.findViewById(R.id.img_radio1);
        ImageView imgRadio2 = (ImageView) rlFeedback.findViewById(R.id.img_radio2);
        ImageView imgRadio3 = (ImageView) rlFeedback.findViewById(R.id.img_radio3);
        ImageView imgRadio4 = (ImageView) rlFeedback.findViewById(R.id.img_radio4);
        ImageView imgRadio5 = (ImageView) rlFeedback.findViewById(R.id.img_radio5);

        ImageView imgDel = (ImageView) rlFeedback.findViewById(R.id.img_del);
        TextView tvConfirm = (TextView) rlFeedback.findViewById(R.id.tv_confirm);

        imgDel.setOnClickListener(v -> {
            mDialog.dismiss();
        });

        tvConfirm.setOnClickListener(v -> {
            mPresenter.cancelOrder(mData.getOmsOrder().getId(), canCelTag);
        });

        rlRadio1.setOnClickListener(v -> {
            canCelTag = "0";
            tvConfirm.setBackgroundResource(R.drawable.violet_round_2dp);
            imgRadio1.setImageDrawable(getResources().getDrawable(R.drawable.pay_radio_sel));
            imgRadio2.setImageDrawable(getResources().getDrawable(R.drawable.pay_radio_no));
            imgRadio3.setImageDrawable(getResources().getDrawable(R.drawable.pay_radio_no));
            imgRadio4.setImageDrawable(getResources().getDrawable(R.drawable.pay_radio_no));
            imgRadio5.setImageDrawable(getResources().getDrawable(R.drawable.pay_radio_no));
        });
        rlRadio2.setOnClickListener(v -> {
            canCelTag = "1";
            tvConfirm.setBackgroundResource(R.drawable.violet_round_2dp);
            imgRadio1.setImageDrawable(getResources().getDrawable(R.drawable.pay_radio_no));
            imgRadio2.setImageDrawable(getResources().getDrawable(R.drawable.pay_radio_sel));
            imgRadio3.setImageDrawable(getResources().getDrawable(R.drawable.pay_radio_no));
            imgRadio4.setImageDrawable(getResources().getDrawable(R.drawable.pay_radio_no));
            imgRadio5.setImageDrawable(getResources().getDrawable(R.drawable.pay_radio_no));
        });
        rlRadio3.setOnClickListener(v -> {
            canCelTag = "2";
            tvConfirm.setBackgroundResource(R.drawable.violet_round_2dp);
            imgRadio1.setImageDrawable(getResources().getDrawable(R.drawable.pay_radio_no));
            imgRadio2.setImageDrawable(getResources().getDrawable(R.drawable.pay_radio_no));
            imgRadio3.setImageDrawable(getResources().getDrawable(R.drawable.pay_radio_sel));
            imgRadio4.setImageDrawable(getResources().getDrawable(R.drawable.pay_radio_no));
            imgRadio5.setImageDrawable(getResources().getDrawable(R.drawable.pay_radio_no));
        });
        rlRadio4.setOnClickListener(v -> {
            canCelTag = "3";
            tvConfirm.setBackgroundResource(R.drawable.violet_round_2dp);
            imgRadio1.setImageDrawable(getResources().getDrawable(R.drawable.pay_radio_no));
            imgRadio2.setImageDrawable(getResources().getDrawable(R.drawable.pay_radio_no));
            imgRadio3.setImageDrawable(getResources().getDrawable(R.drawable.pay_radio_no));
            imgRadio4.setImageDrawable(getResources().getDrawable(R.drawable.pay_radio_sel));
            imgRadio5.setImageDrawable(getResources().getDrawable(R.drawable.pay_radio_no));
        });
        rlRadio5.setOnClickListener(v -> {
            canCelTag = "4";
            tvConfirm.setBackgroundResource(R.drawable.violet_round_2dp);
            imgRadio1.setImageDrawable(getResources().getDrawable(R.drawable.pay_radio_no));
            imgRadio2.setImageDrawable(getResources().getDrawable(R.drawable.pay_radio_no));
            imgRadio3.setImageDrawable(getResources().getDrawable(R.drawable.pay_radio_no));
            imgRadio4.setImageDrawable(getResources().getDrawable(R.drawable.pay_radio_no));
            imgRadio5.setImageDrawable(getResources().getDrawable(R.drawable.pay_radio_sel));
        });

    }

    @Override
    public void getOrderInfo(OrderListDetailBean orderListDetailBean) {
        mData = orderListDetailBean;
        showData(orderListDetailBean);
    }

    /**
     * 取消订单成功
     *
     * @param msg
     */
    @Override
    public void cancelOrder(String msg) {
        ToastUtil.showToast(msg);
    }

    /**
     * 确认收货成功
     *
     * @param msg
     */
    @Override
    public void receiptedOrder(String msg) {
        finish();
    }

    private void showData(OrderListDetailBean orderListDetailBean) {
        //订单状态：-1->已取消 ;0->待付款；1->待发货；2->已发货(待收货)；
        // 3->已完成；4->已关闭；5->无效订单;6->维权中;7->完成交易;8->已完成退款;9->已完成退款退货
        switch (orderListDetailBean.getOmsOrder().getStatus()) {
            case "0":
                mBinding.tvTitle.setText("等待支付");
                mBinding.tvSubtitle.setText("剩15分自动关闭");
                mBinding.tvSubtitle.setVisibility(View.VISIBLE);
                showNoPayment();
                setNoPaymentData(orderListDetailBean);
                break;
            case "1":
                mBinding.tvTitle.setText("待发货");
                mBinding.tvSubtitle.setVisibility(View.GONE);
                showNoSendOut();
                setNoSendOutData(orderListDetailBean);
                break;
            case "2":
                mBinding.tvTitle.setText("待收货");
                mBinding.tvSubtitle.setText("已送达后，" + orderListDetailBean.getOmsOrder().getAutoConfirmDay() + "天自动确认收货");
                mBinding.tvSubtitle.setVisibility(View.VISIBLE);
                showReceive();
                setReceiveData(orderListDetailBean);
                break;
            case "3":
                mBinding.tvTitle.setText("已确认收货/完成交易");
                mBinding.tvSubtitle.setVisibility(View.GONE);
                showReceived();
                setReceivedData(orderListDetailBean);
                break;
        }

        mBinding.tvAddressPeopleName.setText(orderListDetailBean.getOmsOrder().getReceiverName()); //接收人姓名
        mBinding.tvAddressName.setText(orderListDetailBean.getOmsOrder().getReceiverDetailAddress()); //接收人地址
        mBinding.tvAddressPeoplePhone.setText(orderListDetailBean.getOmsOrder().getReceiverPhone()); //接收人电话

        mBinding.tvOrderGoodsMoneyOrderDetails.setText("¥" + orderListDetailBean.getOmsOrder().getTotalAmount()); //商品总额
        mBinding.tvFreight.setText("¥" + orderListDetailBean.getOmsOrder().getFreightAmount()); //总运费
        mBinding.tvDeduction.setText("¥" + orderListDetailBean.getOmsOrder().getPromotionAmount()); //抵扣金额

        String money = "¥" + orderListDetailBean.getOmsOrder().getPayAmount();
        SpannableString spannableString = new SpannableString(money);
        RelativeSizeSpan span1 = new RelativeSizeSpan(0.8f);
        RelativeSizeSpan span2 = new RelativeSizeSpan(0.6f);
        spannableString.setSpan(span1, 0, 1, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
//        spannableString.setSpan(span2, money.indexOf("."), money.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        mBinding.tvPaymentMoney.setText(spannableString);//实付金额
    }

    /**
     * 待支付底部布局
     */
    private void showNoPayment() {
        mBinding.tvOrderNumberOrderDetails.setText(mData.getOmsOrder().getOrderSn()); //订单编号
        mBinding.tvOrderCreateTimeOrderDetails.setText(mData.getOmsOrder().getCreateTime()); //下单时间

        mBinding.rlOrderNumberOrderDetails.setVisibility(View.VISIBLE); //订单编号
        mBinding.rlOrderCreateTimeOrderDetails.setVisibility(View.VISIBLE); //下单时间

        mBinding.rlNoPayment.setVisibility(View.VISIBLE);
        mBinding.tvCancelOrder.setOnClickListener(v -> { //取消订单
            mDialog.show();
        });
        mBinding.tvToPay.setOnClickListener(v -> { //去付款
            ToastUtil.showToast("去付款");
        });
    }

    /**
     * 待发货底部布局
     */
    private void showNoSendOut() {
        mBinding.tvOrderNumberOrderDetails.setText(mData.getOmsOrder().getOrderSn()); //订单编号
        mBinding.tvOrderCreateTimeOrderDetails.setText(mData.getOmsOrder().getCreateTime()); //下单时间
        mBinding.tvOrderPayTimeOrderDetails.setText(mData.getOmsOrder().getPaymentTime()); //付款时间
        mBinding.tvGiveOutAddress.setText(""); //发货地址 todo 未找到发货地址字段

        mBinding.rlOrderNumberOrderDetails.setVisibility(View.VISIBLE); //订单编号
        mBinding.rlOrderCreateTimeOrderDetails.setVisibility(View.VISIBLE); //下单时间
        mBinding.rlOrderPayTimeOrderDetails.setVisibility(View.VISIBLE); //付款时间
        mBinding.rlGiveOutAddress.setVisibility(View.VISIBLE); //发货地址

        mBinding.rlNoSendOut.setVisibility(View.VISIBLE);
        mBinding.tvApplicationRefund.setOnClickListener(v -> { //申请退款 状态
            ARouter.getInstance().build(ARouterPath.PATH_MINE_ORDER_DETAIL_REFUND_PROGRESS)
                    .navigation();
        });
        mBinding.tvContactService.setOnClickListener(v -> { //联系客服
            call(mData.getCustomerPhone());
        });
    }

    /**
     * 待收货底部布局
     */
    private void showReceive() {
        mBinding.tvOrderNumberOrderDetails.setText(mData.getOmsOrder().getOrderSn()); //订单编号
        mBinding.tvOrderCreateTimeOrderDetails.setText(mData.getOmsOrder().getCreateTime()); //下单时间
        mBinding.tvOrderPayTimeOrderDetails.setText(mData.getOmsOrder().getPaymentTime()); //付款时间
        mBinding.tvOrderDeliverTimeOrderDetails.setText(mData.getOmsOrder().getDeliveryTime()); //发货时间
        mBinding.tvGiveOutAddress.setText(""); //发货地址 todo 未找到发货地址字段
        mBinding.tvDeliveryWay.setText(mData.getOmsOrder().getDeliveryCompany()); //配送方式
        mBinding.tvExpressNum.setText(mData.getOmsOrder().getDeliverySn()); //快递单号

        mBinding.rlOrderNumberOrderDetails.setVisibility(View.VISIBLE); //订单编号
        mBinding.rlOrderCreateTimeOrderDetails.setVisibility(View.VISIBLE); //下单时间
        mBinding.rlOrderPayTimeOrderDetails.setVisibility(View.VISIBLE); //付款时间
        mBinding.rlOrderDeliverTimeOrderDetails.setVisibility(View.VISIBLE); //发货时间
        mBinding.rlGiveOutAddress.setVisibility(View.VISIBLE); //发货地址
        mBinding.rlDeliveryWay.setVisibility(View.VISIBLE); //配送方式
        mBinding.rlExpressNum.setVisibility(View.VISIBLE); //快递单号

        mBinding.rlReceive.setVisibility(View.VISIBLE);
        mBinding.tvLogistics.setOnClickListener(v -> { //查看物流
            ARouter.getInstance()
                    .build(ARouterPath.PATH_MINE_ORDER_LOGISTICS)
                    .withInt(MineOrderLogisticsActivity.KEY_ORDER_ID, Integer.parseInt(mData.getOmsOrder().getId()))
                    .navigation();
        });
        mBinding.tvReceiveContactService.setOnClickListener(v -> { //联系客服
            call(mData.getCustomerPhone());
        });
        mBinding.tvConfirmReceive.setOnClickListener(v -> { //确认收货
            mPresenter.obtainGoods(Integer.parseInt(mData.getOmsOrder().getId()));
        });
    }

    /**
     * 已收货底部布局
     */
    private void showReceived() {
        mBinding.tvOrderNumberOrderDetails.setText(mData.getOmsOrder().getOrderSn()); //订单编号
        mBinding.tvOrderCreateTimeOrderDetails.setText(mData.getOmsOrder().getCreateTime()); //下单时间
        mBinding.tvOrderPayTimeOrderDetails.setText(mData.getOmsOrder().getPaymentTime()); //付款时间
        mBinding.tvOrderDeliverTimeOrderDetails.setText(mData.getOmsOrder().getDeliveryTime()); //发货时间
        mBinding.tvOrderOkTimeOrderDetails.setText(mData.getOmsOrder().getReceiveTime());  //送达时间
        mBinding.tvReceiptTime.setText(mData.getOmsOrder().getReceiveTime()); //确认收货 时间 todo 未找到确认收货 时间字段
        mBinding.tvGiveOutAddress.setText(""); //发货地址 todo 未找到发货地址字段
        mBinding.tvDeliveryWay.setText(mData.getOmsOrder().getDeliveryCompany()); //配送方式
        mBinding.tvExpressNum.setText(mData.getOmsOrder().getDeliverySn()); //快递单号

        mBinding.rlOrderNumberOrderDetails.setVisibility(View.VISIBLE); //订单编号
        mBinding.rlOrderCreateTimeOrderDetails.setVisibility(View.VISIBLE); //下单时间
        mBinding.rlOrderPayTimeOrderDetails.setVisibility(View.VISIBLE); //付款时间
        mBinding.rlOrderDeliverTimeOrderDetails.setVisibility(View.VISIBLE); //发货时间
        mBinding.rlOrderOkTimeOrderDetails.setVisibility(View.VISIBLE);  //送达时间
        mBinding.rlReceiptTime.setVisibility(View.VISIBLE); //确认收货 时间
        mBinding.rlGiveOutAddress.setVisibility(View.VISIBLE); //发货地址
        mBinding.rlDeliveryWay.setVisibility(View.VISIBLE); //配送方式
        mBinding.rlExpressNum.setVisibility(View.VISIBLE); //快递单号

        mBinding.rlReceived.setVisibility(View.VISIBLE);
        mBinding.tvMore.setOnClickListener(v -> { //更多
            //弹出选项卡
        });
        mBinding.tvDelOrder.setOnClickListener(v -> { //删除订单

        });
        mBinding.tvLookOverLogistics.setOnClickListener(v -> { //查看物流
            ARouter.getInstance()
                    .build(ARouterPath.PATH_MINE_ORDER_LOGISTICS)
                    .withInt(MineOrderLogisticsActivity.KEY_ORDER_ID, Integer.parseInt(mData.getOmsOrder().getId()))
                    .navigation();
        });
    }

    /**
     * 调用拨号界面
     *
     * @param phone 电话号码
     */
    private void call(String phone) {
        Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phone));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }


    /**
     * 设置待付款 Adapter数据
     *
     * @param orderListDetailBean
     */
    private void setNoPaymentData(OrderListDetailBean orderListDetailBean) {
        //头部布局
        SectionMultipleItem s1 = new SectionMultipleItem(true, orderListDetailBean);
        s1.setOrderListDetailBean(orderListDetailBean);
        list.add(s1);
        //添加中间布局
        for (int j = 0; j < orderListDetailBean.getOrderProducts().size(); j++) {
            SectionMultipleItem sm = new SectionMultipleItem(SectionMultipleItem.CONTENT, orderListDetailBean.getOrderProducts().get(j));
            list.add(sm);
        }
        //添加最后一个item
        SectionMultipleItem sm = new SectionMultipleItem(SectionMultipleItem.CONTENT_ADDITION, null);
        list.add(sm);
        setAdapter();
    }

    /**
     * 设置待发货 Adapter数据
     *
     * @param orderListDetailBean
     */
    private void setNoSendOutData(OrderListDetailBean orderListDetailBean) {
        //头部布局
        SectionMultipleItem s1 = new SectionMultipleItem(true, orderListDetailBean);
        s1.setOrderListDetailBean(orderListDetailBean);
        list.add(s1);
        //添加中间布局
        for (int j = 0; j < orderListDetailBean.getOrderProducts().size(); j++) {
            SectionMultipleItem sm = new SectionMultipleItem(SectionMultipleItem.CONTENT, orderListDetailBean.getOrderProducts().get(j));
            list.add(sm);
        }
        setAdapter();
    }

    /**
     * 设置待收货 Adapter数据
     *
     * @param orderListDetailBean
     */
    private void setReceiveData(OrderListDetailBean orderListDetailBean) {
        //头部布局
        SectionMultipleItem s1 = new SectionMultipleItem(true, orderListDetailBean);
        s1.setOrderListDetailBean(orderListDetailBean);
        list.add(s1);
        //添加中间布局
        for (int j = 0; j < orderListDetailBean.getOrderProducts().size(); j++) {
            SectionMultipleItem sm = new SectionMultipleItem(SectionMultipleItem.CONTENT, orderListDetailBean.getOrderProducts().get(j));
            list.add(sm);
        }
        setAdapter();
    }

    /**
     * 设置已收货 Adapter数据
     *
     * @param orderListDetailBean
     */
    private void setReceivedData(OrderListDetailBean orderListDetailBean) {
        //头部布局
        SectionMultipleItem s1 = new SectionMultipleItem(true, orderListDetailBean);
        s1.setOrderListDetailBean(orderListDetailBean);
        list.add(s1);
        //添加中间布局
        for (int j = 0; j < orderListDetailBean.getOrderProducts().size(); j++) {
            SectionMultipleItem sm = new SectionMultipleItem(SectionMultipleItem.CONTENT_RECEIVE, orderListDetailBean.getOrderProducts().get(j));
            list.add(sm);
        }

        setAdapter();
    }

    private void setAdapter() {
        mBinding.mineOrderDetailsList.setLayoutManager(new LinearLayoutManager(this));
        mAdapter = new OrderDetailAdapter(R.layout.mine_item_order_detail_header, list);
        mBinding.mineOrderDetailsList.setAdapter(mAdapter);

        mAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                if (view.getId() == R.id.tv_contact_service) { //item 联系客服
                    call(mData.getCustomerPhone());
                } else if (view.getId() == R.id.tv_after_sale) {
                    // 售后申请
                    ARouter.getInstance()
                            .build(ARouterPath.PATH_MINE_ORDER_AFTER_SALES_REQUEST)
                            .withInt(MineOrderAfterSalesRequestActivity.KEY_ID, Integer.parseInt(mData.getOrderProducts().get(0).getId()))
                            .navigation();
                }

            }
        });
    }


}
